package com.bac.rentmap.web.controller.osmimport;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.bac.rentmap.manager.BuildingManager;
import com.bac.rentmap.model.Building;
import com.bac.rentmap.osm.BuildingsReader;

/**
 *
 * @author Ivan Holub
 */
public class ImportBuildingsServiceController extends AbstractController {

	private BuildingManager buildingManager;

	private BuildingsReader buildingsReader;

	public void setBuildingManager(BuildingManager buildingManager) {
		this.buildingManager = buildingManager;
	}

	public void setBuildingsReader(BuildingsReader buildingsReader) {
		this.buildingsReader = buildingsReader;
	}

	protected ModelAndView handleRequestInternal(
			HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse) throws Exception {

		String numberParam = httpServletRequest.getParameter("number");
		int number = Integer.valueOf(numberParam);
		String city = httpServletRequest.getParameter("city");
		int maxNumber = buildingManager.getMaxNumber(city);

		int fromIndex = maxNumber;
		List<Building> buildings = buildingsReader
				.readBuildings(getServletContext(), fromIndex, number, city);

		if (!buildings.isEmpty()) {
			buildingManager.saveBuildings(buildings, city);
		}

		maxNumber = buildingManager.getMaxNumber(city);

		ModelAndView mav = new ModelAndView(
				"admin/import/osm/importbuildingsservice");
		mav.addObject("maxNumber", maxNumber);
		return mav;
	}
}